const app = getApp();
const Chart = require('./chart/chart.js');
const rpx2px = (rpx) => { return rpx / 750 * app.globalData.sysInfo.screenWidth };
// myChart/myChart.js
Component({
	/**
	 * 组件的属性列表
	 */
	properties: {
		data: {
			type: Array,
			observer: '_handleDataChange'
		},
		config: {
			type: Object,
		}
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		cw: 0,
		ch: 0,
		ctx: null,
		chart: null,
		isFirst: true,
		valueArray: []
	},

	/**
	 * 组件的方法列表
	 */
	methods: {
		_handleDataChange (newV) {
			if (!this.data.isFirst) {
				this.setData({
					valueArray: [...this.data.chart.updateData(newV).points]
				}, () => {
					console.log(this.data.valueArray);
				})
			}
		},
		startDraw () {
			let chart = new Chart({
				data: this.data.data,
				config: {
					width: this.data.cw,
					height: this.data.ch,
					fontSize: rpx2px(20),
					axis: {
						color: '#eeeeee',
						lineWidth: 1,
						lineColor: '#eeeeee',
						x: {
							variable: 'text',
							isHideBetween: this.data.data.length >= 10,
							unit: '时',
							color: '#aaaaaa'
						},
						y: {
							variable: 'value',
							unit: '笔',
							count: 4,
							color: '#aaaaaa'
						},
						average: {
							color: '#d4d4d4',
							array: [8, 8],
							offset: 5
						}
					},
					point: {
						color: '#fcac05',
						lineWidth: rpx2px(4),
						lineColor: '#fbb21b',
						fontSize: rpx2px(20),
						scalePoint: true, // 是否放大该点
						radius: rpx2px(4), // scalePoint为true时点的半径
					},
					text: {
						color: '#aaaaaa',
						fontSize: rpx2px(20),
						x: this.data.cw, y: rpx2px(30),
						marginBot: rpx2px(30)
					}
				},
				ctx: this.data.ctx
			});

			this.setData({
				chart,
				isFirst: false,
				valueArray: [...chart.points]
			})
		},

		// 选择查看数据
		onChooseViewData (e) {
			console.log(e);
		}
	},

	ready () {
		let ctx = wx.createCanvasContext('chart', this);
		wx.createSelectorQuery().in(this).select("#myChart_wrapper").boundingClientRect((res) => {
			this.setData({
				cw: res.width,
				ch: res.height,
				ctx
			}, () => {
				this.startDraw();
			})
		}).exec();
	}
})
